#include "TcpHandleTask.h"

int Call::TcpHandleTask::CountLinkNum()
{
    return m_tasks.size();
}

bool Call::TcpHandleTask::Create()
{
    Call::Config config;

    WS::TcpServer::Desc desc;
    desc.port = config.tcpPort;

    SV_FAILED(tcpServer.Create(desc));

    LOGI("task Create successfully");

    return true;
}

void Call::TcpHandleTask::Run()
{
    while (1)
    {
        OnAccept(tcpServer.Accept());
    }
}

Call::TcpClientTask *Call::TcpHandleTask::RegisterHost(const WS::TcpSocket &socket)
{
    auto res = new TcpClientTask(socket);
    return res;
}

void Call::TcpHandleTask::LockTaskList()
{
    std::lock_guard<std::mutex> lock(m_task_mutex);
}

Call::TcpHandleTask::~TcpHandleTask()
{
    for (auto &task : m_tasks)
    {
        delete task;
    }
}

void Call::TcpHandleTask::OnAccept(const WS::TcpSocket &socket)
{
    LOGI("host port %s %d", socket.IP(), socket.Port());

    LockTaskList();

    auto task = new TcpClientTask(socket);
    task->Start();
    this->m_tasks.push_back(task);
};
